<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Franchise_model extends CI_Model {

    public function loadFranchise($data = array(), $sort = array('name' => 'ASC')) {
        $this->db->select("*");
        $this->db->from("franchise");

        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $this->db->where($key, $value);
            }
        }

        if (!empty($sort)) {
            foreach ($sort as $key => $value) {
                $this->db->order_by($key, $value);
            }
        }
        
        if(!empty($group_by)){
            $this->db->group_by($group_by);
        }
        
        
        
        $query = $this->db->get();
        
        return $query->result();
    }

    public function getFrachiseById( $id ) {
        $result = $this->loadFranchise(array('id' => $id));
        if (!empty($result))
            return $result[0];
        return FALSE;
    }

    function distance($lat1, $lon1, $lat2, $lon2, $u = '1') {
        $u = strtolower($u);
        if ($u == 'k') {
            $u = 1.609344;
        } // kilometers
        elseif ($u == 'n') {
            $u = 0.8684;
        } // nautical miles
        elseif ($u == 'm') {
            $u = 1;
        } // statute miles (default)
        $d = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2));
        $d = rad2deg(acos($d));
        $d = $d * 60 * 1.1515;
        $d = ($d * $u); // apply unit
        $d = round($d); // optional
        return $d;
    }

    public function getOfficeNearest($lat, $lon) {
        $this->db->select("*, (((acos(sin((" . $lat . "*pi()/180)) * 
            sin((`lat`*pi()/180))+cos((" . $lat . "*pi()/180)) * 
            cos((`lat`*pi()/180)) * cos(((" . $lon . " - `long`)* 
            pi()/180))))*180/pi())*60*1.1515
        ) as distance");
        $this->db->from("franchise");
        $this->db->order_by('distance', 'ASC');
        $this->db->limit(1);
        $query = $this->db->get();
        $result = $query->result();
        return $result[0];
    }

}